package com.vinoxm.rss.subscribe.handler;

import com.vinoxm.rss.model.RssResult;
import com.vinoxm.rss.model.RssSubscribe;
import com.vinoxm.rss.rest.RestClient;
import com.vinoxm.rss.subscribe.vo.SubscribeBase;
import lombok.extern.log4j.Log4j2;
import org.json.JSONObject;
import org.json.XML;

import java.net.URL;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;

@Log4j2
public abstract class AbstractSubscribeHandler {

    public final List<RssResult> doHandler(RssSubscribe rssSubs) {
        try {
            String res = RestClient.getRssSubscribeByUrl(rssSubs.getUrl(), String.class);
            JSONObject json = XML.toJSONObject(res);
            SubscribeBase rssVo = convertJsonToRssVo(json);
            return null != rssVo ? getRssItems(rssVo, rssSubs.getId(), rssSubs.getRegex()) : Collections.emptyList();
        } catch (Exception e) {
            return null;
        }
    }

    public final boolean containsUrl(URL url) {
        return Pattern.matches(getUrlRegex(), url.getHost());
    }

    protected final List<RssResult> emptyResultList() {
        return Collections.emptyList();
    }

    protected abstract String getUrlRegex();

    protected abstract SubscribeBase convertJsonToRssVo(JSONObject json);

    protected abstract List<RssResult> getRssItems(SubscribeBase rssVo, Long pid, String regexStr);

}
